import { isNotEmpty } from "jsmethod-extra";

const jsSrcRegex = /<script\b[^>]*\s+src=["']([^"']+)["']/gi;
const cssHrefRegex = /<link\b[^>]*\s+href=["']([^"']+)["'][^>]*>/gi;
const imgSrcRegex = /<img\b[^>]*\s+src=["']([^"']+)["'][^>]*>/gi;
const svgHrefRegex =
  /<svg\b[^>]*>(?:(?!<\/svg>)[\s\S])*<image\b[^>]*\s+href=["']([^"']+)["'][^>]*>/gi;

/**
 * @author lihh
 * @description 解析剖析 html 中的元素
 */
export class ExtractHtmlElement {
  private readonly htmlString: string;
  private static instance: ExtractHtmlElement;

  constructor(htmlString: string) {
    this.htmlString = htmlString;
  }

  public static getInstance(htmlString: string): ExtractHtmlElement {
    if (isNotEmpty(ExtractHtmlElement.instance)) {
      return ExtractHtmlElement.instance;
    }
    return (ExtractHtmlElement.instance = new ExtractHtmlElement(htmlString));
  }

  /**
   * @author lihh
   * @description 正则解析 共同的部分
   * @param regExp 正则解析
   * @private 私有的
   */
  private handleCommon(regExp: RegExp): Array<string> {
    const srcMatches: Array<string> = [];
    let srcMatch;

    while ((srcMatch = regExp.exec(this.htmlString)) !== null) {
      srcMatches.push(srcMatch[1]);
    }

    return srcMatches.map((l) => (l.startsWith("./") ? l.slice(1) : l));
  }

  /**
   * @author lihh
   * @description 解析css 内容
   */
  public css(): Array<string> {
    return this.handleCommon(cssHrefRegex);
  }

  public js(): Array<string> {
    return this.handleCommon(jsSrcRegex);
  }

  public all(): Array<string> {
    return [...this.css(), ...this.js()];
  }
}
